package com.portomx.agenda.dao.impl;

import java.util.Collection;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.portomx.agenda.commons.AppException;
import com.portomx.agenda.dao.PersonaDao;
import com.portomx.agenda.model.Persona;

@Repository
public class PersonaDaoImpl implements PersonaDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Transactional
	@Override
	public void create(Persona persona) {
		try {
			Assert.notNull(persona);
			sessionFactory.getCurrentSession().save(persona);
		} catch (Exception ex) {
			throw new AppException("Error al guardar los datos", ex);
		}
	}

	@Transactional
	@Override
	public void update(Persona persona) {
		try {
			this.sessionFactory.getCurrentSession().update(persona);
		} catch (Exception ex) {
			throw new AppException("Error al actualizar los datos", ex);
		}
	}

	@Transactional
	@Override
	public void delete(Persona persona) {
		try {
			this.sessionFactory.getCurrentSession().delete(persona);
		} catch (Exception ex) {
			throw new AppException("Error al eliminar los datos", ex);
		}
	}

	@Transactional
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Persona> getAll() {
		Session session = null;
		try {
			session = sessionFactory.openSession();
			return session.createQuery("from Persona").list();
		} catch (Exception ex) {
			throw new AppException(
					"Error al recuperar la coleccion de objetos "
							+ ex.getMessage());
		}
	}

	@Override
	public Collection<Persona> findBy(Map<String, Object> parametros) {
		// TODO Auto-generated method stub
		return null;
	}

	@Transactional(readOnly = true)
	@Override
	public Persona read(Long id) {
		return (Persona) this.sessionFactory.getCurrentSession()
				.createQuery("from Persona p where p.id= :id").setLong("id", id)
				.uniqueResult();
	}

}
